Imports ExpertPdf.HtmlToPdf

Partial Class _Default
    Inherits System.Web.UI.Page

    ''' <summary>
    ''' Convert the HTML code from the specified URL to a PDF document and send the 
    ''' document as an attachment to the browser
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConvertURLToPDF()

        Dim urlToConvert As String = textBoxWebPageURL.Text.Trim()
        Dim selectablePDF As Boolean = radioConvertToSelectablePDF.Checked

        ' Create the PDF converter. Optionally you can specify the virtual browser 
        ' width as parameter. 1024 pixels is default, 0 means autodetect
        Dim pdfConverter As PdfConverter = New PdfConverter()
        ' set the license key
        'pdfConverter.LicenseKey = "put your license key here"
        ' set the converter options
        pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4
        pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal
        pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait

        ' set if header and footer are shown in the PDF - optional - default is false 
        pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked
        pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked
        ' set to generate a pdf with selectable text or a pdf with embedded image - optional - default is true
        pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = radioConvertToSelectablePDF.Checked
        ' set if the HTML content is resized if necessary to fit the PDF page width - optional - default is true
        pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked

        ' set the embedded fonts option - optional - default is false
        pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked
        ' set the live HTTP links option - optional - default is true
        pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked

        If (radioConvertToSelectablePDF.Checked) Then
            ' set if the JavaScript is enabled during conversion to a PDF with selectable text 
            ' - optional - default is false
            pdfConverter.ScriptsEnabled = cbClientScripts.Checked
            ' set if the ActiveX controls (like Flash player) are enabled during conversion 
            ' to a PDF with selectable text - optional - default is false
            pdfConverter.ActiveXEnabled = cbActiveXEnabled.Checked
        Else
            ' set if the JavaScript is enabled during conversion to a PDF with embedded image 
            ' - optional - default is true
            pdfConverter.ScriptsEnabledInImage = cbClientScripts.Checked
            ' set if the ActiveX controls (like Flash player) are enabled during conversion 
            ' to a PDF with embedded image - optional - default is true
            pdfConverter.ActiveXEnabledInImage = cbActiveXEnabled.Checked
        End If

        ' set if the images in PDF are compressed with JPEG to reduce the PDF document size - optional - default is true
        pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked

        ' enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2)
        If (cbBookmarks.Checked) Then
            pdfConverter.PdfBookmarkOptions.TagNames = New String() {"H1", "H2"}
        End If

        ' set PDF security options - optional
        'pdfConverter.PdfSecurityOptions.CanPrint = True
        'pdfConverter.PdfSecurityOptions.CanEditContent = True
        'pdfConverter.PdfSecurityOptions.UserPassword = ""

        ' set PDF document description - optional
        pdfConverter.PdfDocumentInfo.AuthorName = "Winnovative HTML to PDF Converter"

        ' add HTML header
        If (cbAddHeader.Checked) Then
            AddHeader(pdfConverter)
        End If
        ' add HTML footer
        If (cbAddFooter.Checked) Then
            AddFooter(pdfConverter)
        End If

        ' Performs the conversion and get the pdf document bytes that you can further 
        ' save to a file or send as a browser response
        Dim pdfBytes As Byte() = pdfConverter.GetPdfBytesFromUrl(urlToConvert)

        ' send the PDF document as a response to the browser for download
        Dim Response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        Response.Clear()
        Response.AddHeader("Content-Type", "binary/octet-stream")
        Response.AddHeader("Content-Disposition", "attachment; filename=ConversionResult.pdf; size=" & pdfBytes.Length.ToString())
        Response.Flush()
        Response.BinaryWrite(pdfBytes)
        Response.Flush()
        Response.End()
    End Sub


    ''' <summary>
    ''' Convert the HTML code from the specified URL to a JPEG image and send the 
    ''' image as an attachment to the browser
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConvertURLToImage()
        Dim urlToConvert As String = textBoxWebPageURL.Text.Trim()

        ' Create the Image converter. Optionally you can specify the virtual browser 
        ' width as parameter. 1024 pixels is default, 0 means autodetect
        Dim imgConverter As ImgConverter = New ImgConverter()
        ' set the license key
        'imgConverter.LicenseKey = "put your license key here"

        ' set if the JavaScript is enabled during conversion - optional - default is true
        imgConverter.ScriptsEnabled = cbClientScripts.Checked
        ' set if the ActiveX controls (like Flash player) are enabled during conversion - optional - default is true
        imgConverter.ActiveXEnabled = cbActiveXEnabled.Checked

        ' Performs the conversion and get the image bytes that you can further 
        ' save to a file or send as a browser response
        Dim imgBytes As Byte() = imgConverter.GetImageFromUrlBytes(urlToConvert, System.Drawing.Imaging.ImageFormat.Jpeg)

        ' send the image as a response to the browser for download
        Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        Response.Clear()
        response.AddHeader("Content-Type", "binary/octet-stream")
        response.AddHeader("Content-Disposition", "attachment; filename=ConversionResult.jpeg; size=" & imgBytes.Length.ToString())
        response.Flush()
        response.BinaryWrite(imgBytes)
        response.Flush()
        response.End()
    End Sub


    ''' <summary>
    ''' Convert the specified HTML string to a PDF document and send the 
    ''' document as an attachment to the browser
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConvertHTMLStringToPDF()

        Dim htmlString As String = textBoxHTMLCode.Text
        Dim baseURL As String = textBoxBaseURL.Text.Trim()
        Dim selectablePDF As Boolean = radioConvertToSelectablePDF.Checked

        ' Create the PDF converter. Optionally you can specify the virtual browser 
        ' width as parameter. 1024 pixels is default, 0 means autodetect
        Dim pdfConverter As PdfConverter = New PdfConverter()
        ' set the license key
        'pdfConverter.LicenseKey = "put your license key here"
        ' set the converter options
        pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4
        pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal
        pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait


        ' set if header and footer are shown in the PDF - optional - default is false 
        pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked
        pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked
        ' set to generate a pdf with selectable text or a pdf with embedded image - optional - default is true
        pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = radioConvertToSelectablePDF.Checked
        ' set if the HTML content is resized if necessary to fit the PDF page width - optional - default is true
        pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked

        ' set the embedded fonts option - optional - default is false
        pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked
        ' set the live HTTP links option - optional - default is true
        pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked

        If (radioConvertToSelectablePDF.Checked) Then
            ' set if the JavaScript is enabled during conversion to a PDF with selectable text 
            ' - optional - default is false
            pdfConverter.ScriptsEnabled = cbClientScripts.Checked
            ' set if the ActiveX controls (like Flash player) are enabled during conversion 
            ' to a PDF with selectable text - optional - default is false
            pdfConverter.ActiveXEnabled = cbActiveXEnabled.Checked
        Else
            ' set if the JavaScript is enabled during conversion to a PDF with embedded image 
            ' - optional - default is true
            pdfConverter.ScriptsEnabledInImage = cbClientScripts.Checked
            ' set if the ActiveX controls (like Flash player) are enabled during conversion 
            ' to a PDF with embedded image - optional - default is true
            pdfConverter.ActiveXEnabledInImage = cbActiveXEnabled.Checked
        End If

        ' set if the images in PDF are compressed with JPEG to reduce the PDF document size - optional - default is true
        pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked

        ' enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2)
        If (cbBookmarks.Checked) Then
            pdfConverter.PdfBookmarkOptions.TagNames = New String() {"H1", "H2"}
        End If

        ' set PDF security options - optional
        'pdfConverter.PdfSecurityOptions.CanPrint = True
        'pdfConverter.PdfSecurityOptions.CanEditContent = True
        'pdfConverter.PdfSecurityOptions.UserPassword = ""

        ' set PDF document description - optional
        pdfConverter.PdfDocumentInfo.AuthorName = "Winnovative HTML to PDF Converter"

        ' add HTML header
        If (cbAddHeader.Checked) Then
            AddHeader(pdfConverter)
        End If
        ' add HTML footer
        If (cbAddFooter.Checked) Then
            AddFooter(pdfConverter)
        End If

        ' Performs the conversion and get the pdf document bytes that you can further 
        ' save to a file or send as a browser response
        '
        ' The baseURL parameter helps the converter to get the CSS files and images
        ' referenced by a relative URL in the HTML string. This option has efect only if the HTML string
        ' contains a valid HEAD tag. The converter will automatically inserts a <BASE HREF="baseURL"> tag. 
        Dim pdfBytes As Byte() = Nothing
        If (baseURL.Length > 0) Then
            pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, baseURL)
        Else
            pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString)
        End If

        ' send the PDF document as a response to the browser for download
        Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        response.Clear()
        response.AddHeader("Content-Type", "binary/octet-stream")
        response.AddHeader("Content-Disposition", "attachment; filename=ConversionResult.pdf; size=" & pdfBytes.Length.ToString())
        response.Flush()
        response.BinaryWrite(pdfBytes)
        response.Flush()
        response.End()
    End Sub

    ''' <summary>
    ''' Convert the specified HTML string to a JPEG image and send the
    ''' image as an attachment to the browser
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConvertHTMLStringToImage()
        Dim htmlString As String = textBoxHTMLCode.Text
        Dim baseURL As String = textBoxBaseURL.Text.Trim()

        ' Create the Image converter. Optionally you can specify the virtual browser 
        ' width as parameter. 1024 pixels is default, 0 means autodetect
        Dim imgConverter As ImgConverter = New ImgConverter()
        ' set the license key
        'imgConverter.LicenseKey = "put your license key here"

        ' set if the JavaScript is enabled during conversion - optional - default is true
        imgConverter.ScriptsEnabled = cbClientScripts.Checked
        ' set if the ActiveX controls (like Flash player) are enabled during conversion - optional - default is true
        imgConverter.ActiveXEnabled = cbActiveXEnabled.Checked

        ' Performs the conversion and get the image bytes that you can further 
        ' save to a file or send as a browser response
        '
        ' The baseURL parameter helps the converter to get the CSS files and images
        ' referenced by a relative URL in the HTML string. This option has efect only if the HTML string
        ' contains a valid HEAD tag. The converter will automatically inserts a <BASE HREF="baseURL"> tag. 
        Dim imgBytes As Byte() = Nothing
        If (baseURL.Length > 0) Then
            imgBytes = imgConverter.GetImageBytesFromHtmlString(htmlString, System.Drawing.Imaging.ImageFormat.Jpeg, baseURL)
        Else
            imgBytes = imgConverter.GetImageBytesFromHtmlString(htmlString, System.Drawing.Imaging.ImageFormat.Jpeg)
        End If

        ' send the image as a response to the browser for download
        Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
        Response.Clear()
        response.AddHeader("Content-Type", "binary/octet-stream")
        response.AddHeader("Content-Disposition", "attachment; filename=ConversionResult.jpeg; size=" & imgBytes.Length.ToString())
        response.Flush()
        response.BinaryWrite(imgBytes)
        response.Flush()
        response.End()
    End Sub

    Private Sub AddHeader(ByRef pdfConverter As PdfConverter)
        Dim thisPageURL As String = HttpContext.Current.Request.Url.AbsoluteUri
        Dim headerAndFooterHtmlUrl As String = thisPageURL.Substring(0, thisPageURL.LastIndexOf("/")) + "/HeaderAndFooterHtml.htm"

        'enable header
        pdfConverter.PdfDocumentOptions.ShowHeader = True
        ' set the header height in points
        pdfConverter.PdfHeaderOptions.HeaderHeight = 60
        ' set the header HTML area
        pdfConverter.PdfHeaderOptions.HtmlToPdfArea = New HtmlToPdfArea(0, 0, -1, pdfConverter.PdfHeaderOptions.HeaderHeight, headerAndFooterHtmlUrl, 1024, -1)
        pdfConverter.PdfHeaderOptions.HtmlToPdfArea.FitHeight = True
        pdfConverter.PdfHeaderOptions.HtmlToPdfArea.EmbedFonts = cbEmbedFonts.Checked
    End Sub

    Private Sub AddFooter(ByRef pdfConverter As PdfConverter)
        Dim thisPageURL As String = HttpContext.Current.Request.Url.AbsoluteUri
        Dim headerAndFooterHtmlUrl As String = thisPageURL.Substring(0, thisPageURL.LastIndexOf("/")) + "/HeaderAndFooterHtml.htm"

        'enable footer
        pdfConverter.PdfDocumentOptions.ShowFooter = True
        ' set the footer height in points
        pdfConverter.PdfFooterOptions.FooterHeight = 60
        'write the page number
        pdfConverter.PdfFooterOptions.TextArea = New TextArea(0, 30, "This is page &p; of &P;  ", New System.Drawing.Font(New System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point))
        pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = True
        pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right
        ' set the footer HTML area
        pdfConverter.PdfFooterOptions.HtmlToPdfArea = New HtmlToPdfArea(0, 0, -1, pdfConverter.PdfFooterOptions.FooterHeight, headerAndFooterHtmlUrl, 1024, -1)
        pdfConverter.PdfFooterOptions.HtmlToPdfArea.FitHeight = True
        pdfConverter.PdfFooterOptions.HtmlToPdfArea.EmbedFonts = cbEmbedFonts.Checked
    End Sub

    Protected Sub btnConvert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConvert.Click
        If (radioConvertURL.Checked) Then
            ' convert the HTML from a specified URL
            If (radioConvertToImage.Checked) Then
                ConvertURLToImage() 'convert URL to image
            Else
                ConvertURLToPDF() 'convert URL to PDF
            End If
        Else
            ' convert the specified HTML string
            If (radioConvertToImage.Checked) Then
                ConvertHTMLStringToImage() 'convert HTML string to image
            Else
                ConvertHTMLStringToPDF() 'convert HTML string to PDF
            End If
        End If
    End Sub

    Protected Sub radioConvertURL_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioConvertURL.CheckedChanged
        pnlConvertURL.Visible = radioConvertURL.Checked
        pnlConvertHTML.Visible = Not radioConvertURL.Checked
    End Sub

    Protected Sub radioConvertHTML_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioConvertHTML.CheckedChanged
        pnlConvertURL.Visible = Not radioConvertHTML.Checked
        pnlConvertHTML.Visible = radioConvertHTML.Checked
    End Sub
End Class
